'use strict';
const puppeteer = require('puppeteer');
const Service = require('egg').Service;

class DoubanHotService extends Service {
  async douban() {
    const browser = await puppeteer.launch({
      executablePath: puppeteer.executablePath(),
      headless: false,
    });
    const douban = 'https://movie.douban.com/explore';
    const page = await browser.newPage();
    await page.goto(douban, {
      waitUntil: 'networkidle0',
    });
    const movieList = await page
      .evaluate(async dom => {
        // for (let i = 0; i < 4; i++) {
        //   await new Promise(rel =>
        //     setTimeout(() => {
        //       $('.more').click();
        //       rel();
        //     }, 4000)
        //   );
        // }
        return Array.from($(dom).find('.list a')).map(el => {
          const $el = $(el);
          const detailUrl = $el.attr('href');
          const picUrl = $el.find('img').attr('src');
          const title = $el.find('img').attr('alt');
          const item = { detailUrl, picUrl, title };
          return item;
        });
      }, 'body')
      .catch(err => console.log('err', err));
    await page.close();
    return movieList;
  }
  async runDoubanCrawler() {
    const list = await this.douban();
    await this.ctx.model.Douban.bulkCreate(list);
    return {
      msg: '创建成功～',
    };
  }
  async getAll() {
    return this.ctx.model.Douban.findAll();
  }
}

module.exports = DoubanHotService;
